"""
python fujian1_autoArima_gragh.py
"""

import os
import json
import pandas as pd
import matplotlib.pyplot as plt

# 文件路径
input_dir = os.path.join("fujian", "fujian1", "auto_arima", "result")
output_dir = os.path.join(input_dir, "graph")

# 确保输出目录存在
os.makedirs(output_dir, exist_ok=True)

# 遍历每个 JSON 文件
for file_name in os.listdir(input_dir):
    if file_name.endswith(".json") and file_name.startswith("autoArima_category"):
        category_id = file_name.replace("autoArima_category", "").replace(".json", "")
        
        # 加载 JSON 数据
        with open(os.path.join(input_dir, file_name), "r") as f:
            data = json.load(f)
        
        # 提取日期和库存量
        dates = [item["date"] for item in data]
        inventory = [item["inventory"] for item in data]

        # 创建 DataFrame
        df = pd.DataFrame({
            "date": pd.to_datetime(dates),
            "inventory": inventory
        })

        # 分割原始数据和预测数据
        original_data = df.iloc[:12]  # 前12个月
        forecast_data = df.iloc[12:]  # 后3个月

        # 绘制图形
        plt.figure(figsize=(10, 5))
        plt.plot(original_data["date"], original_data["inventory"], label="Original Data", color="blue", marker='o')
        plt.plot(forecast_data["date"], forecast_data["inventory"], label="Forecast Data", color="orange", marker='o')
        
        # 添加标题和标签
        plt.title(f"Inventory Data for Category {category_id}")
        plt.xlabel("Date")
        plt.ylabel("Inventory")
        plt.xticks(rotation=45)
        plt.legend()
        plt.grid()
        
        # 保存图形
        graph_file_path = os.path.join(output_dir, f"category_{category_id}.png")
        plt.tight_layout()  # 调整图形布局
        plt.savefig(graph_file_path)
        plt.close()  # 关闭图形

        print(f"图形已保存为 {graph_file_path}")

print("所有图形生成完毕！")
